package csv;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * csv工具类
 */
public class CsvUtils {
    private static Logger logger = LoggerFactory.getLogger(CsvUtils.class);
    /**
     * 从csv文件中读取数据，将数据读取到 List<double[]> 中，每行是一个double[]
     * @param fileName 文件名称
     * @param headers 文件头
     * @return List<double[]>
     */
    public static List<Double[]> readCsv(String fileName,String[] headers) {
        List<Double[]> result = new ArrayList<>();
        CSVFormat format = CSVFormat.DEFAULT;
        if(Optional.ofNullable(headers).isPresent()){
            format.withHeader(headers).withSkipHeaderRecord();
        }
        Reader in = null;
        try {
            in = new FileReader(fileName);
            Iterable<CSVRecord> records = format.parse(in);
            for(CSVRecord record:records){
                Double[] r = new Double[record.size()];
                for(int i=0;i<r.length;i++){
                    r[i] = Double.valueOf(record.get(i));
                }
                result.add(r);
            }
        }  catch (IOException e) {
            logger.error("io exception",e);
        }finally {
            if(Optional.ofNullable(in).isPresent()){
                try {
                    in.close();
                } catch (IOException ioException) {
                    logger.error("close reader error",ioException);
                }
            }
        }
        return result;
    }

    /**
     * 将data内容写入csv文件
     * @param fileName 要写入的csv文件名称
     * @param headers 写入的headers
     * @param datas 需要写入的数据
     */
    public static void writeCsv(String fileName,String[] headers,List<Double[]> datas) {
        Writer out = null;
        try {
            CSVFormat format = CSVFormat.DEFAULT.withHeader(headers);
            out = new FileWriter(fileName);
            CSVPrinter printer = new CSVPrinter(out, format);
            for (Double[] data : datas) {
                printer.printRecord(data);
            }
        }catch(IOException e){
            logger.error("io exception",e);
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.error("io exception",e);
            }
        }
    }
}
